package com.hdoit.apollo.web.billing.apis;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.billing.model.Billing;
import com.hdoit.apollo.logical.billing.model.BillingRecord;
import com.hdoit.apollo.logical.billing.service.IBillingRecordService;
import com.hdoit.apollo.logical.billing.service.IBillingService;
import com.hdoit.apollo.logical.cargo.model.Cargo;
import com.hdoit.apollo.logical.common.enums.billing.BillingConfirm;
import com.hdoit.apollo.logical.common.enums.billing.BillingRecordType;
import com.hdoit.apollo.logical.common.enums.billing.BillingState;
import com.hdoit.apollo.logical.common.enums.billing.IsDelivery;
import com.hdoit.apollo.logical.common.enums.billing.IsGathering;
import com.hdoit.apollo.logical.common.enums.billing.PayState;
import com.hdoit.apollo.logical.common.enums.shop.CustomerRecordType;
import com.hdoit.apollo.logical.shop.service.ICustomerRecordService;
import com.hdoit.apollo.logical.stock.model.OutStock;
import com.hdoit.apollo.logical.stock.model.OutStockShow;
import com.hdoit.apollo.logical.stock.service.IOutStockCollocationService;
import com.hdoit.apollo.logical.viewmodel.billing.BillingRecordSearch;
import com.hdoit.apollo.logical.viewmodel.billing.BillingSearch;
import com.hdoit.apollo.logical.viewmodel.billing.BillingStat;
import com.tennetcn.authority.component.webapi.BaseApi;
import com.tennetcn.authority.component.webapi.ResponseModel;
import com.tennetcn.authority.component.webapi.ResponseStatus;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.core.common.utils.JsonUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping(value = "/api/v1/billing/",method = { RequestMethod.GET,RequestMethod.POST},produces = "application/json;charset=UTF-8")
@CrossOrigin(origins = "*", maxAge = 3600)
@Api(value="/api/v1/billing")
public class BillingApi extends BaseApi{

	@Autowired
	private IBillingService billingService;
	
	@Autowired
	private IBillingRecordService billingRecordService;
	
	@Autowired
	private ICustomerRecordService customerRecordService;
	
	@Autowired
	private IOutStockCollocationService outStockCollocationService;
	
	private final String saveBillingApi="saveBilling";
	private final String getBillingsByScrollApi="getBillingsByScroll";
	private final String getBillingInfoByCargoIdApi="getBillingInfoByCargoId";
	private final String getBillingsByKey="getBillingsByKey";
	private final String closeBillingByKey="closeBillingByKey";
	private final String checkBillingByKey="checkBillingByKey";
	private final String getBillingRecord="getBillingRecord";
	private final String getBillingStat="getBillingStat";
	private final String queryBillingStat="queryBillingStat";
	private final String querySaleCargoListApi="querySaleCargoList";
	
	
	private final String getBillingInfoListByCustomerIdApi="getBillingInfoListByCustomerId";
	
    @RequestMapping(value = saveBillingApi)
    @ApiOperation(notes = saveBillingApi, httpMethod = "POST", value = "保存开单信息")
    public @ResponseBody String saveBilling(Billing billing,String outStockShowsJson,String outStockJson){
    	Billing billingPan = billingService.queryModel(billing.getBillingId());
    	String timestamp = DateUtils.convertDate2String("yyyyMMddHHmmss", DateUtils.getCurrent());
    	billing.setUnpaidAmount(billing.getBillingMoney());
    	billing.setPayState(PayState.unpaid);
    	if(billingPan==null){
    		if(BillingState.returnCargo.equals(billing.getBillingState())) {
    			billing.setBillingNo("TQH-"+timestamp);
    		}
    		if(BillingState.returnOfCargo.equals(billing.getBillingState())) {
    			billing.setBillingNo("TH-"+timestamp);
    		}
    		if(BillingState.notShipped.equals(billing.getBillingState())) {
    			billing.setBillingNo("KD-"+timestamp);
    		}
    		billing.setConfirm(BillingConfirm.unCheck);
    		billing.setIsDelivery(Integer.parseInt(IsDelivery.weifahuo));
    		billing.setIsGathering(Integer.parseInt(IsGathering.weishoukuan));
            billing.setDeleteMark(YesOrNoInteger.no);
            billing.setCreateDate(DateUtils.getCurrent());
            billing.setCreateUserId(getLoginId());
            billing.setCreateUserName(getLoginName());
            billing.setModelStatus(ModelStatus.add);
    	}else{
    		billing.setModifyUserId(getLoginId());
    		billing.setModifyUserName(getLoginName());
    		billing.setModifyDate(DateUtils.getCurrent());
    		billing.setModelStatus(ModelStatus.update);
    	}

    	
    	ResponseModel rm=new ResponseModel();
    	if(BillingState.returnCargo.equals(billing.getBillingState())) {
    		OutStock outStock= (OutStock) JsonUtils.readValue(outStockJson,  OutStock.class);
        	if(!billingService.applyBillingReturn(billing,outStock)){
        		rm.setStatus(ResponseStatus.dataError);
        	}
    	}else {
        	
        	@SuppressWarnings("unchecked")
    		List<OutStockShow> outStockShows = (List<OutStockShow>) JsonUtils.readValues(outStockShowsJson, List.class, OutStockShow.class);
        	if(!billingService.applyBilling(billing,outStockShows)){
        		rm.setStatus(ResponseStatus.dataError);
        	}
    	}

    	return rm.toJson();
    }
    
    
    @RequestMapping(value = getBillingInfoByCargoIdApi)
    @ApiOperation(notes = getBillingInfoByCargoIdApi, httpMethod = "GET", value = "获取货架欠货订单列表")
    public @ResponseBody String getBillingInfoByCargoId(String cargoId){
    	List<Billing> billings = billingService.getBillingInfoByCargoId(cargoId);
    	ResponseModel rm=new ResponseModel();
    	rm.put("billings",billings);
    	return rm.toJson();
    }

    
    @RequestMapping(value = getBillingInfoListByCustomerIdApi)
    @ApiOperation(notes = getBillingInfoListByCustomerIdApi, httpMethod = "GET", value = "获取客户订单列表")
    public @ResponseBody String getBillingInfoListByCustomerId(String customerId){
    	List<Billing> billings = billingService.getBillingInfoListByCustomerId(customerId);
    	ResponseModel rm=new ResponseModel();
    	rm.put("billings",billings);
    	return rm.toJson();
    }
    
 	@RequestMapping(value = getBillingsByScrollApi)
    @ApiOperation(notes = getBillingsByScrollApi, httpMethod = "POST", value = "滚动查找订单信息列表")
    public @ResponseBody String getBillingsByScrollApi(BillingSearch search,int dataPosition,int pageSize){
    	ResponseModel rm=new ResponseModel();
    	PagerModel pagerModel=null;
    	if(pageSize!=0){
    		int pageindex = (dataPosition%pageSize==0?dataPosition/pageSize:dataPosition/pageSize+1)+1;
    		pagerModel = new PagerModel(pageSize, pageindex);
    	}else{
    		pagerModel=new PagerModel();
    	}

    	List<Billing> billings=billingService.queryListMP(search, pagerModel);
    	
    	rm.put("billings",billings);
    	return rm.toJson();
    }
 	
    @RequestMapping(value = getBillingsByKey)
    @ApiOperation(notes = getBillingsByKey, httpMethod = "GET", value = "通过id获取订单信息")
    public @ResponseBody String getBillingsByKey(String key){
    	Billing billing =billingService.getBillingByKey(key);
    	ResponseModel rm=new ResponseModel();
    	rm.put("billing",billing);
    	return rm.toJson();
    }
    
    @RequestMapping(value = closeBillingByKey)
    @ApiOperation(notes = closeBillingByKey, httpMethod = "GET", value = "通过id获取关闭订单")
    public @ResponseBody String closeBillingByKey(String key){
    	Billing billing =billingService.queryModel(key);
    	billing.setBillingState(BillingState.close);
    	billing.setModelStatus(ModelStatus.update);
    	
    	billingRecordService.saveBillingRecord(billing.getBillingId(),0.0,0.0,BillingRecordType.close,
				"",billing.getShopId(),getLoginId(),getLoginName());
    	
    	customerRecordService.saveCustomerRecord(billing.getCustomerId(),billing.getBillingMoney(),0.0,CustomerRecordType.close,
				billing.getBillingId(),billing.getShopId(),getLoginId(),getLoginName());
    	
    	ResponseModel rm=new ResponseModel();
    	if(!billingService.applyChange(billing)){
    		rm.setStatus(ResponseStatus.dataError);
    	}
    	return rm.toJson();
    }
    
    @RequestMapping(value = checkBillingByKey)
    @ApiOperation(notes = checkBillingByKey, httpMethod = "GET", value = "通过id获取审核订单")
    public @ResponseBody String checkBillingByKey(String key){
    	Billing billing =billingService.queryModel(key);
    	billing.setConfirm(BillingConfirm.checked);
    	billing.setModelStatus(ModelStatus.update);
    	
    	billingRecordService.saveBillingRecord(billing.getBillingId(),0.0,0.0,BillingRecordType.check,
				"",billing.getShopId(),getLoginId(),getLoginName());

    	ResponseModel rm=new ResponseModel();
    	if(!billingService.applyChange(billing)){
    		rm.setStatus(ResponseStatus.dataError);
    	}
    	return rm.toJson();
    }
    
    @RequestMapping(value = getBillingRecord)
    @ApiOperation(notes = getBillingRecord, httpMethod = "GET", value = "通过billingId获取订单操作信息")
    public @ResponseBody String getBillingRecord(BillingRecordSearch search){
    	List<BillingRecord> billingRecords=billingRecordService.queryListMP(search, null);
    	ResponseModel rm=new ResponseModel();
    	rm.put("billingRecords",billingRecords);
    	return rm.toJson();
    }
    
    @RequestMapping(value = getBillingStat)
    @ApiOperation(notes = getBillingStat, httpMethod = "GET", value = "查找home页面统计信息")
    public @ResponseBody String getBillingStat(BillingSearch search){
    	search.setStartDate(DateUtils.getCurrent());
    	search.setEndDate(DateUtils.getCurrent());
    	BillingStat billingStat=billingService.getBillingStat(search);
    	ResponseModel rm=new ResponseModel();
    	rm.put("billingStat",billingStat);
    	return rm.toJson();
    }
    @RequestMapping(value = queryBillingStat)
    @ApiOperation(notes = queryBillingStat, httpMethod = "GET", value = "销售报表")
    public @ResponseBody String queryBillingStat(BillingSearch search){
    	search.setType("notShipped");
    	search.setBillingState(BillingState.completed);
    	BillingStat billingStat=outStockCollocationService.querySummaryStat(search);
    	ResponseModel rm=new ResponseModel();
    	rm.put("billingStat",billingStat);
    	return rm.toJson();
    }
    
    @RequestMapping(value = querySaleCargoListApi)
    @ApiOperation(notes = querySaleCargoListApi, httpMethod = "GET", value = "销售货物报表")
    public @ResponseBody String querySaleCargoList(BillingSearch search){
    	search.setType("notShipped");
    	search.setBillingState(BillingState.completed);
    	System.err.println(search.getSearchType()+"EEEEEEE");
    	List<Cargo> cargos=outStockCollocationService.querySaleCargoList(search);
    	ResponseModel rm=new ResponseModel();
    	rm.put("cargos",cargos);
    	return rm.toJson();
    }
    
}
